function handleFocus(e) {
  const cell = e.target;
  cell.focus();
  cell.select();
}

// 处理失焦事件
function handleBlur(e) {
  const cell = e.target;
  // 更新数据模型
  const row = Math.floor(
    Array.from(cell.parentNode.children).indexOf(cell) / matrixData[0].length
  );
  const col =
    Array.from(cell.parentNode.children).indexOf(cell) % matrixData[0].length;
  matrixData[row][col] = parseInt(cell.textContent) || 0;
}

// 复制功能
function copyToClipboard() {
  // 从DOM中获取当前矩阵内容
  const cells = document.querySelectorAll(".matrix-cell");
  let text = "";
  cells.forEach((cell, index) => {
    text += cell.textContent;
    if ((index + 1) % matrixData[0].length !== 0) {
      text += " ";
    }
    if (
      (index + 1) % matrixData[0].length === 0 &&
      index !== cells.length - 1
    ) {
      text += "\n";
    }
  });

  // 复制到剪贴板
  navigator.clipboard
    .writeText(text)
    .then(() => {
      console.log("复制成功");
    })
    .catch((err) => {
      console.error("复制失败:", err);
    });
}

// 粘贴功能
async function pasteFromClipboard() {
  try {
    const text = await navigator.clipboard.readText();
    const lines = text.split("\n");
    const newData = [];

    lines.forEach((line) => {
      const cells = line.split(" ").filter((cell) => cell.trim() !== "");
      if (cells.length > 0) {
        newData.push(cells.map((cell) => parseInt(cell) || 0));
      }
    });

    // 更新数据模型
    matrixData = newData;
    generateMatrix();
    console.log("粘贴成功");
  } catch (err) {
    console.error("粘贴失败:", err);
  }
}

// 初始化矩阵
// generateMatrix();

// 添加全局键盘事件监听
document.addEventListener("keydown", (e) => {
  if (e.ctrlKey && e.key === "c") {
    e.preventDefault();
    copyToClipboard();
  }
  if (e.ctrlKey && e.key === "v") {
    e.preventDefault();
    pasteFromClipboard();
  }
});

// 处理方向键导航
document.addEventListener("keydown", (e) => {
  if (
    e.key === "ArrowUp" ||
    e.key === "ArrowDown" ||
    e.key === "ArrowLeft" ||
    e.key === "ArrowRight"
  ) {
    const focusedCell = document.activeElement;
    if (focusedCell.classList.contains("matrix-cell")) {
      const row = Math.floor(
        Array.from(focusedCell.parentNode.children).indexOf(focusedCell) /
          matrixData[0].length
      );
      const col =
        Array.from(focusedCell.parentNode.children).indexOf(focusedCell) %
        matrixData[0].length;
      let newRow = row;
      let newCol = col;

      switch (e.key) {
        case "ArrowUp":
          newRow = Math.max(0, row - 1);
          break;
        case "ArrowDown":
          newRow = Math.min(matrixData.length - 1, row + 1);
          break;
        case "ArrowLeft":
          newCol = Math.max(0, col - 1);
          break;
        case "ArrowRight":
          newCol = Math.min(matrixData[0].length - 1, col + 1);
          break;
      }

      const newCell = document.querySelector(
        `.matrix-cell:nth-child(${newRow * matrixData[0].length + newCol + 1})`
      );
      if (newCell) {
        newCell.focus();
        newCell.select();
      }
      e.preventDefault();
    }
  }
});

document.querySelectorAll('mn[contenteditable="true"]').forEach((element) => {
  element.addEventListener("blur", function () {
    console.log("编辑完成:", this.textContent);
    // 这里可以添加保存逻辑或其他处理
  });

  element.addEventListener("input", function () {
    console.log("正在编辑:", this.textContent);
  });
});
